package com.ruanxie.controller.user;

import com.ruanxie.constant.JwtClaimsConstant;
import com.ruanxie.constant.MessageConstant;
import com.ruanxie.dto.user.UserLoginDTO;
import com.ruanxie.entity.User;
import com.ruanxie.exception.AccountNotFoundException;
import com.ruanxie.properties.JwtProperties;
import com.ruanxie.result.Result;
import com.ruanxie.service.UserService;
import com.ruanxie.utils.JwtUtil;
import com.ruanxie.vo.user.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户相关接口
 */
@RestController
@RequestMapping("/api/user")
@Api(tags = "用户相关接口")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;//jwt令牌相关配置

    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);
        User user = userService.login(userLoginDTO);
        //存在用户生成jwt令牌
        //TODO 尝试：优化：若角色为学生，能否将专业那些信息也放进去
        //但是一开始还没做教务导入，后面再回来看
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.accountId, user.getAccountId());
        claims.put(JwtClaimsConstant.role, user.getRole());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);
        log.info("jwt令牌生成成功：{}", token);
        UserLoginVO userLoginVO = new UserLoginVO();
        BeanUtils.copyProperties(user, userLoginVO);
        userLoginVO.setToken(token);
        return Result.success(userLoginVO);
    }

    @PostMapping("/logout")
    @ApiOperation("员工退出")
    public Result<String> logout() {
        return Result.success();
    }
}
